<?php

class SensibleController extends Controller {

    protected $layout = "index";
    protected $auto_safe = true;

    public function handleRequest($prefix, $method, $arguments) {
        if (!method_exists($this, $prefix."_".$method)) {
            Event::run('system.404');
            return;
        }
        $result = call_user_func_array(array($this, $prefix."_".$method), $arguments);
        
        if ($result instanceof Result && (request::is_ajax() || is_null($this->layout))) {
            $view = new MY_Smarty_Core(kohana::find_file('views',$result->getTemplate(true),true,'tpl'));
            $view->assign($result->getArgs());
            $view->assign('this',$result);
            $view->assign('controller', $this);
            $view->assign('controllerName', str_replace('_Controller','',get_class($this)));
            echo $view;
        } else
        if ($result instanceof Result && !request::is_ajax()) {
            $layout = $this->getLayout();
            $view = new MY_Smarty_Core(kohana::find_file('views',$result->getTemplate(true),true,'tpl'));
            $view->assign($result->getArgs());
            $view->assign('this',$result);
            $view->assign('controller', $this);
            $view->assign('controllerName', str_replace('_Controller','',get_class($this)));
            $layout->controllerName=$result->getController();
            $layout->content = $view;
            echo $layout;
        } else
        if ($result instanceof View && !request::is_ajax()) {
            $layout = $this->getLayout();
            $layout->content = $result;
            echo $layout;
        } else
        if ($result instanceof View && request::is_ajax()) {
            echo $result;
        } else {
            echo $result;
        }
    }

    protected function getLayout() {
        if ($file = Kohana::find_file('layouts', $this->layout)) {
            require_once $file;
            $className = ucfirst($this->layout)."_Layout";
            $layoutObject = new $className();
            $layoutObject->layout = $layoutObject;
            $layoutObject->controller = $this;
            return $layoutObject;
        } else throw new Exception('"'.$this->layout.'" layout not found');
    }

}